const multer = require('multer');
const path = require('path');
const fs = require('fs');
const config = require('../config/default');
const logger = require('../utils/logger');

// 确保上传目录存在
const uploadDir = config.fileStorage;
if (!fs.existsSync(uploadDir)) {
  try {
    fs.mkdirSync(uploadDir, { recursive: true });
    logger.info(`创建上传目录: ${uploadDir}`);
  } catch (error) {
    logger.error(`创建上传目录失败: ${error.message}`);
  }
}

// 配置存储引擎
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    // 生成唯一文件名
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    const ext = path.extname(file.originalname);
    cb(null, file.fieldname + '-' + uniqueSuffix + ext);
  }
});

// 文件过滤器 - 只允许特定类型的文件
const fileFilter = (req, file, cb) => {
  // 定义允许的文件类型
  const allowedTypes = [
    'image/jpeg', 
    'image/png', 
    'image/gif', 
    'application/pdf',
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'application/vnd.ms-excel',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  ];
  
  if (allowedTypes.includes(file.mimetype)) {
    cb(null, true);
  } else {
    cb(new Error(`不支持的文件类型: ${file.mimetype}`), false);
  }
};

// 创建 Multer 实例
const upload = multer({
  storage: storage,
  fileFilter: fileFilter,
  limits: {
    fileSize: 10 * 1024 * 1024 // 限制文件大小为10MB
  }
});

// 错误处理中间件 - 捕获 multer 错误
const handleUploadErrors = (err, req, res, next) => {
  if (err instanceof multer.MulterError) {
    if (err.code === 'LIMIT_FILE_SIZE') {
      return res.status(400).json({ 
        success: false, 
        message: '文件大小超出限制（最大10MB）' 
      });
    }
    return res.status(400).json({ 
      success: false, 
      message: `上传文件错误: ${err.message}` 
    });
  }
  
  if (err) {
    return res.status(400).json({ 
      success: false, 
      message: err.message 
    });
  }
  
  next();
};

module.exports = {
  upload,
  handleUploadErrors
}; 